import json
import re
from typing import Any, Dict, List, Optional, Union
import logging


def setup_logging(level: str = "INFO") -> logging.Logger:
    """设置日志配置"""
    logging.basicConfig(
        level=getattr(logging, level.upper()),
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    return logging.getLogger(__name__)


def clean_text(text: str) -> str:
    """清理文本内容"""
    if not text:
        return ""
    
    # 去除多余的空白字符
    text = re.sub(r'\s+', ' ', text.strip())
    
    # 去除特殊字符
    text = re.sub(r'[^\w\s\u4e00-\u9fff.,!?;:()"\'-]', '', text)
    
    return text


def extract_json_from_text(text: str) -> Optional[Dict[str, Any]]:
    """从文本中提取JSON数据"""
    try:
        # 尝试直接解析整个文本
        return json.loads(text)
    except json.JSONDecodeError:
        pass
    
    # 尝试从文本中提取JSON片段
    json_pattern = r'\{.*\}'
    matches = re.findall(json_pattern, text, re.DOTALL)
    
    for match in matches:
        try:
            return json.loads(match)
        except json.JSONDecodeError:
            continue
    
    return None


def format_currency(amount: float, currency: str = "CNY") -> str:
    """格式化货币显示"""
    if currency == "CNY":
        return f"¥{amount:.2f}"
    elif currency == "USD":
        return f"${amount:.2f}"
    else:
        return f"{amount:.2f} {currency}"


def truncate_text(text: str, max_length: int = 100, suffix: str = "...") -> str:
    """截断文本"""
    if len(text) <= max_length:
        return text
    
    return text[:max_length - len(suffix)] + suffix


def parse_query_params(query: str) -> Dict[str, Any]:
    """解析查询参数（增强版）"""
    params = {}
    query_lower = query.lower()
    
    # 提取城市名称（扩展城市列表）
    cities = [
        '北京', '上海', '广州', '深圳', '杭州', '南京', '武汉', '成都', 
        '重庆', '西安', '天津', '青岛', '大连', '厦门', '苏州', '无锡',
        '宁波', '长沙', '郑州', '济南', '合肥', '福州', '东莞', '佛山'
    ]
    
    for city in cities:
        if city in query:
            params['city'] = city
            break
    
    # 分析查询类型（更精确的关键词匹配）
    if any(keyword in query_lower for keyword in ['时间', '几点', '现在', '当前时间', '什么时候']):
        params['query_type'] = 'time'
    elif any(keyword in query_lower for keyword in ['天气', '温度', '下雨', '晴天', '阴天', '多云', '风', '湿度']):
        params['query_type'] = 'weather'
    elif any(keyword in query_lower for keyword in ['退货', '退款', '返回', '退掉', '不要了', '退回', '退货政策']):
        params['query_type'] = 'return_policy'
    elif any(keyword in query_lower for keyword in ['配送', '快递', '发货', '物流', '送货', '多久', '几天', '配送时间']):
        params['query_type'] = 'shipping'
    elif any(keyword in query_lower for keyword in ['支付', '付款', '安全', '支付宝', '微信', '银行卡']):
        params['query_type'] = 'payment'
    elif any(keyword in query_lower for keyword in ['会员', '权益', '积分', '折扣', '优惠', '特权']):
        params['query_type'] = 'membership'
    elif any(keyword in query_lower for keyword in ['发票', '开票', '报销', '税票', '电子发票']):
        params['query_type'] = 'invoice'
    elif any(keyword in query_lower for keyword in ['换货', '更换', '调换', '换个']):
        params['query_type'] = 'exchange'
    elif any(keyword in query_lower for keyword in ['保修', '维修', '质保', '坏了', '故障', '修理']):
        params['query_type'] = 'warranty'
    elif any(keyword in query_lower for keyword in ['客服', '联系', '电话', '咨询', '人工']):
        params['query_type'] = 'contact'
    elif any(keyword in query_lower for keyword in ['订单', '发货状态', '物流信息']):
        params['query_type'] = 'order'
    else:
        params['query_type'] = 'general'
    
    # 提取订单号
    import re
    order_pattern = r'\b\d{10,15}\b'
    order_matches = re.findall(order_pattern, query)
    if order_matches:
        params['order_id'] = order_matches[0]
    
    return params


def validate_email(email: str) -> bool:
    """验证邮箱格式"""
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return bool(re.match(pattern, email))


def validate_phone(phone: str) -> bool:
    """验证手机号格式"""
    pattern = r'^1[3-9]\d{9}$'
    return bool(re.match(pattern, phone))


def mask_sensitive_info(text: str) -> str:
    """掩码敏感信息"""
    # 掩码手机号
    text = re.sub(r'1[3-9]\d{9}', lambda m: m.group()[:3] + '****' + m.group()[-4:], text)
    
    # 掩码邮箱
    text = re.sub(r'([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})', 
                  lambda m: m.group().split('@')[0][:2] + '***@' + m.group().split('@')[1], text)
    
    # 掩码身份证号
    text = re.sub(r'\d{17}[\dXx]', lambda m: m.group()[:6] + '********' + m.group()[-4:], text)
    
    return text


def calculate_similarity(text1: str, text2: str) -> float:
    """计算文本相似度（简单实现）"""
    if not text1 or not text2:
        return 0.0
    
    # 转换为小写并分词
    words1 = set(clean_text(text1.lower()).split())
    words2 = set(clean_text(text2.lower()).split())
    
    # 计算交集和并集
    intersection = words1.intersection(words2)
    union = words1.union(words2)
    
    if not union:
        return 0.0
    
    return len(intersection) / len(union)


def format_response_for_display(response: Dict[str, Any]) -> str:
    """格式化响应用于显示"""
    if response.get('type') == 'json':
        try:
            content = json.loads(response['content']) if isinstance(response['content'], str) else response['content']
            return json.dumps(content, ensure_ascii=False, indent=2)
        except (json.JSONDecodeError, TypeError):
            return str(response['content'])
    
    return str(response.get('content', ''))


def get_file_extension(filename: str) -> str:
    """获取文件扩展名"""
    return filename.split('.')[-1].lower() if '.' in filename else ''


def is_valid_url(url: str) -> bool:
    """验证URL格式"""
    url_pattern = r'^https?://(?:[-\w.])+(?:[:\d]+)?(?:/(?:[\w/_.])*(?:\?(?:[\w&=%.])*)?(?:#(?:\w*))?)?$'
    return bool(re.match(url_pattern, url))


class ResponseFormatter:
    """响应格式化器"""
    
    @staticmethod
    def format_error(error_message: str, error_code: str = "GENERAL_ERROR") -> Dict[str, Any]:
        """格式化错误响应"""
        return {
            "status": "error",
            "error_code": error_code,
            "message": error_message,
            "timestamp": _get_current_timestamp()
        }
    
    @staticmethod
    def format_success(data: Any, message: str = "操作成功") -> Dict[str, Any]:
        """格式化成功响应"""
        return {
            "status": "success",
            "message": message,
            "data": data,
            "timestamp": _get_current_timestamp()
        }
    
    @staticmethod
    def format_tool_result(tool_name: str, result: Any) -> Dict[str, Any]:
        """格式化工具调用结果"""
        return {
            "tool_name": tool_name,
            "result": result,
            "timestamp": _get_current_timestamp()
        }


def _get_current_timestamp() -> str:
    """获取当前时间戳"""
    import datetime
    return datetime.datetime.now().isoformat()
